package com.controller;

import domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.attribute.UserDefinedFileAttributeView;

@Controller
@RequestMapping("/user")
public class response {
    /*
    * 返回一个String类型*/
    @RequestMapping("/string")
    public String responseString(){
        System.out.println("String响应成功。。");
        return "success";
    }
    /*
    * 返回void类型*/
    @RequestMapping("/void")
    public void responseVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1. 通过请求转发
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //2. 通过重定向，不能访问web-inf目录下的文件
        //response.sendRedirect(request.getContextPath()+"/index.jsp");
       //3 通过输出流直接响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("你好！");

        System.out.println("void响应成功。。");
        return;
    }
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        ModelAndView mv=new ModelAndView();
        User user=new User();
        user.setAge(18);
        user.setUsername("小明");
        user.setPassword("123");
        mv.addObject("user",user);
        //通过ModelAndView 返回，之前返回字符串的底层方式就是它
        mv.setViewName("success");
        return mv;
    }
    @RequestMapping("/stringForwordandRedirect")
    public String stringForwordandRedirect(){
        System.out.println("stringForwordandRedirect方法执行了。。");
        //不使用视图解析器来进行跳转
        //return "forward:/WEB-INF/pages/success.jsp";
        return "redirect:/index.jsp";//项目名在spring会帮你加上的
    }
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了。。。");
        System.out.println(user);
        //使用了jar包将json串自动转为Java对象
       // System.out.println(body);
        //响应客服端,这里是模拟响应查询数据库
        //使用@ResponseBody注解进行响应：将user对象转为json对象
        user.setAge(20);
        user.setUsername("haha");
        return user;
    }
}
